const express = require('express');
const router = express.Router();
const {asyncHandler} = require('../utils/sendResult');
const userService = require("../services/userServices")
const JwtTool = require("../utils/jwtTool")
const {ValidationError} = require("../utils/customError");

// 用户注册
router.post("/register",asyncHandler(async (req,res,next)=>{
    return  userService.registerUser(req.body)
}))

// 判断用户是否存在
router.get("/isLoginId/:loginId",asyncHandler((req,res,next)=>{
   return userService.getIsLoginById(req.params.id)
}))

// 用户登录
router.post("/",asyncHandler(async (req,res,next)=>{
    const result = await userService.loginUser(req.body)
    if(!result){
        // 如果不存在 则抛出错误
        throw new ValidationError("账号密码错误")
    }
    JwtTool.generate(res,1000 * 60 * 60 * 24 * 3,result.toJSON())
    return result
}))

// 修改用户信息
router.post("/:id",asyncHandler((req,res,next)=>{
    return userService.editUserInfoById(req.params.id,req.body)
}))


// 获取用户列表
router.get("/",asyncHandler((req,res,next)=>{
    return userService.getUserByPage(req.query)
}))

// 删除用户
router.delete("/:id",asyncHandler((req,res,next)=>{
    return userService.deleteUserInfoById(req.params.id)
}))

module.exports = router;
